/*

File: SFExportController.m

Version: 1.0

Disclaimer: IMPORTANT:  This Apple software is supplied to you by Apple
Inc. ("Apple") in consideration of your agreement to the
following terms, and your use, installation, modification or
redistribution of this Apple software constitutes acceptance of these
terms.  If you do not agree with these terms, please do not use,
install, modify or redistribute this Apple software.

In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a personal, non-exclusive
license, under Apple's copyrights in this original Apple software (the
"Apple Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software. 
Neither the name, trademarks, service marks or logos of Apple Inc.
may be used to endorse or promote products derived from the Apple
Software without specific prior written permission from Apple.  Except
as expressly stated in this notice, no other rights or licenses, express
or implied, are granted by Apple herein, including but not limited to
any patent rights that may be infringed by your derivative works or by
other works in which the Apple Software may be incorporated.

The Apple Software is provided by Apple on an "AS IS" basis.  APPLE
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.

IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.

Copyright © 2007 Apple Inc. All Rights Reserved

*/

#import "SFExportController.h"
#import <QuickTime/QuickTime.h>
#import <Foundation/Foundation.h>

@implementation SFExportController

- (void)awakeFromNib
{
	int a = 5;
	a++;
	
}

- (id)initWithExportImageObj:(id <ExportImageProtocol>)obj
{
	if(self = [super init])
	{
		mExportMgr = obj;
		mProgress.message = nil;
		mProgressLock = [[NSLock alloc] init];
		mOpenPanel = [NSOpenPanel openPanel];
	}
	return self;
}

- (void)dealloc
{
	[mExportDir release];
	[mProgressLock release];
	[mProgress.message release];
	
	[super dealloc];
}


- (IBAction) choosePath:sender
{
	[mOpenPanel setCanChooseFiles:NO];
	[mOpenPanel setCanChooseDirectories:YES];
	[mOpenPanel setAllowsMultipleSelection:NO];
	NSInteger openResponse = [mOpenPanel runModalForDirectory:nil file:nil types:nil];
	if (openResponse == NSOKButton)
	{
		NSArray* fileNamesArray = [mOpenPanel filenames];
		if ([fileNamesArray count] >= 1)
		{
			[self setExportDir: [fileNamesArray objectAtIndex:0]];
			[mPathField setStringValue:[self exportDir]];
			NSLog(@"Set export directory: %@",[self exportDir]);
		}
	}
	
}

// getters/setters
- (NSString *)exportDir
{
	return mExportDir;
}

- (void)setExportDir:(NSString *)dir
{
	[mExportDir release];
	mExportDir = [dir retain];
}

// protocol implementation
- (NSView <ExportPluginBoxProtocol> *)settingsView
{
	return mSettingsBox;
}

- (NSView *)firstView
{
	return mFirstView;
}

- (void)viewWillBeActivated
{

}

- (void)viewWillBeDeactivated
{

}

- (NSString *)requiredFileType
{
	// Always a directory, directories will be made inside
	return @"";
}

- (BOOL)wantsDestinationPrompt
{
	return NO;
}

- (NSString*)getDestinationPath
{
	// Not important since wantsDestinationPrompt is YES
	return @"";
}

- (NSString *)defaultFileName
{
	if([mExportMgr imageCount] > 1)
		return @"";
	else
		return @"sfe-0";
}

- (NSString *)defaultDirectory
{
	return @"~/Pictures/";
}

- (BOOL)treatSingleSelectionDifferently
{
	return NO;
}

- (BOOL)handlesMovieFiles
{
	return NO;
}

- (BOOL)validateUserCreatedPath:(NSString*)path
{
	// Path must exist
	return NO;
}

- (void)clickExport
{
	[mExportMgr clickExport];
}

- (void)startExport:(NSString *)path
{
		
	// Get values from UI
	[self setExportDir: [mPathField stringValue]];
	NSLog(@"Using Base Directory: %@", [self exportDir]);
	
	mCancelOnError = [mCancelonErrorCheck state] == NSOnState;
	NSLog(@"Cancel on Error: %d", mCancelOnError);
	
	mPreview = [mPreviewCheck state] == NSOnState;
	NSLog(@"Preview: %d", mPreview);
	
	mFilter = [mFilterField stringValue];
	NSLog(@"Using filter value: %@",mFilter);
	
	mDateFormat = [mDateField stringValue];
	NSLog(@"Using date format value: %@",mDateFormat);
	
	
	// Find all paths
	
	
	
	
	// Set variables
	int count = [mExportMgr imageCount];
	mExportFilenames = [NSMutableArray arrayWithCapacity:count];
	[mExportFilenames retain];
	BOOL succeeded = YES;
	mCancelExport = NO;
	NSFileManager* fileManager = [NSFileManager defaultManager];
	
	// Loop through images
	unsigned int i;
	for (i=0;mCancelExport==NO && succeeded==YES && i<count; i++)
	{
		
		BOOL doItem = YES;
		
		// Do the translation
		NSString* builtString = [self translateFilter:i	filter:mFilter];
		NSLog(@"builtString: %@",builtString);
		
		// Put together the string
		NSString* destPath = [[self exportDir] stringByAppendingPathComponent:builtString];
		NSLog(@"Destination: %@", destPath); 
		
		
		// Make sure destination file doesn't exist
		NSString *sourcePath = [mExportMgr sourcePathAtIndex:i];
		NSLog(@"Checking source file does exist: %@",sourcePath);
		NSLog(@"Checking destination file doesn't exist: %@",destPath);
		
		if (![fileManager fileExistsAtPath:sourcePath])
		{
			NSLog(@"Source file doesn't exist: %@",sourcePath);
		}
		
		if ([fileManager fileExistsAtPath:destPath])
		{
			NSLog(@"File already exists at destination: %@",destPath);
			NSString* errMsg = [NSString stringWithFormat:@"Replace existing file?: %@",destPath];
			if (NSRunCriticalAlertPanel(@"File exists",  
										errMsg,
										@"Replace", nil, @"Cancel")==NSAlertOtherReturn) 
			{
				doItem = NO;
			}
		}
		
		if (doItem)
		{
			// Add to array
			[destPath retain];
			[mExportFilenames addObject:destPath];
			
		} 
		else
		{
			[mExportFilenames addObject:nil];
		}
		
	}
	
	
	[mExportMgr startExport];
}


- (void)performExport:(NSString *)path
{
	// Logging
	NSLog(@"performExport");
	NSLog(@"performExport path: %@", path);
	NSLog(@"Using filter: %@",mFilter);
	
	// Set variables
	int count = [mExportMgr imageCount];
	BOOL succeeded = YES;
	mCancelExport = NO;
	NSFileManager* fileManager = [NSFileManager defaultManager];
	
	// Set message
	[self lockProgress];
	mProgress.indeterminateProgress = NO;
	mProgress.totalItems = 1;//count - 1;
	[mProgress.message autorelease];
	mProgress.message = @"Exporting";
	[self unlockProgress];
	
	// Loop through images
	unsigned int i;
	for (i=0;mCancelExport==NO && succeeded==YES && i<count; i++)
	{
		// Set message
		[self lockProgress];
		mProgress.currentItem = i;
		[mProgress.message autorelease];
		mProgress.message = [[NSString stringWithFormat:@"Item %u of %u",i+1,count] retain];
		[self unlockProgress];
		
		// Get the destination path
		NSString* destPath = [mExportFilenames objectAtIndex:i];
		
		if (destPath != nil && !mPreview)
		{
			
			NSError* itemExportError = nil;
			NSString *sourcePath = [mExportMgr sourcePathAtIndex:i];
			NSLog(@"Moving %@ to %@",sourcePath,destPath);
			
			// Create directories if necessary
			NSString* destDirectory = [destPath stringByDeletingLastPathComponent];
			BOOL destDirIsDirectory;
			BOOL destDirExists = [fileManager fileExistsAtPath:destDirectory isDirectory:&destDirIsDirectory];
			if (!destDirExists)
			{
				NSError* createDirectoryErr;
				BOOL createDirectorySuccess = [fileManager createDirectoryAtPath:destDirectory withIntermediateDirectories:YES attributes:nil error:&createDirectoryErr];
				if (!createDirectorySuccess)
				{
					itemExportError = createDirectoryErr;
				}
			}
			
			// Delete previous file if necessary, make sure we're not deleting a directory
			// @todo: Handle (destExists && destIsDirectory) more informatively
			BOOL destIsDirectory;
			BOOL destExists = [fileManager fileExistsAtPath:destPath isDirectory:&destIsDirectory];
			if (destExists && !destIsDirectory)
			{
				NSError* deleteErr = nil;
				NSLog(@"Deleting existing file: %@",destPath);
				BOOL deleteSuccess = [fileManager removeItemAtPath:destPath error:&deleteErr];
				if (!deleteSuccess)
				{
					itemExportError = deleteErr;
				}
			}
			
			// Copy the file
			if (itemExportError == nil && !(destExists && destIsDirectory))
			{
				NSError* copyErr = nil;
				BOOL copySuccess = [fileManager copyItemAtPath:sourcePath toPath:destPath error:&copyErr];
				
				if (!copySuccess)
				{
					itemExportError = copyErr;
				}
				
			}
			
			// Handle errors
			if (itemExportError == nil)
			{
				NSLog(@"Item Export Successful");
			}
			else
			{
				NSLog(@"Item Export Unsuccessful: %@",itemExportError);
				
				[self lockProgress];
				[mProgress.message autorelease];
				mProgress.message = [[NSString stringWithFormat:@"Unable to create %@", destPath] retain];
				if (mCancelOnError)
				{
					mProgress.shouldCancel = YES;
					mCancelExport = TRUE;
					[self cancelExport];
				}
				[self unlockProgress];
			}
			
		}
		
		[destPath release];
	}
	
	// close the progress panel when done
	[self lockProgress];
	[mProgress.message autorelease];
	mProgress.message = nil;
	mProgress.shouldStop = YES;
	[self unlockProgress];
	
	// cleanup
	[mExportFilenames release];
}


- (NSString *) translateFilter:(unsigned int)imageid filter:(NSString*)filter
{
	
	NSLog(@"translateFilter: %u, %@",imageid,filter);
	NSLog(@"Image Index: %u", imageid);
	
	// Get image information
	NSString* imgTitle = [mExportMgr imageTitleAtIndex:imageid];
	NSString* imgComments = [mExportMgr imageCommentsAtIndex:imageid];
	NSString* imgFilename = [mExportMgr imageFileNameAtIndex:imageid];
	NSDate* imgDate = [mExportMgr imageDateAtIndex:imageid];
	NSString* imgDateStr = [imgDate descriptionWithCalendarFormat:mDateFormat timeZone:nil locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]];
	NSString* imgFileExt = [imgFilename pathExtension];
	NSString* 
	
	NSLog(@"Title: %@",imgTitle);
	NSLog(@"Comments: %@",imgComments);
	NSLog(@"Filename: %@",imgFilename);
	NSLog(@"Extension: %@",imgFileExt);
	NSLog(@"Date: %@",imgDateStr);
	
	// Replace items
	NSMutableString* result = [[NSMutableString alloc] init];
	int filterLength = [filter length];
	int i;
	for (i = 0; i < filterLength - 1;i++)
	{
		if ([[filter substringWithRange:NSMakeRange(i,2)] isEqualToString:@"%t"])
		{
			[result appendString:imgTitle];
			i++;
		} 
		else if ([[filter substringWithRange:NSMakeRange(i,2)] isEqualToString:@"%c"])
		{
			[result appendString:imgComments];
			i++;
		}
		else if ([[filter substringWithRange:NSMakeRange(i,2)] isEqualToString:@"%f"])
		{
			[result appendString:imgFilename];
			i++;
		}
		else if ([[filter substringWithRange:NSMakeRange(i,2)] isEqualToString:@"%d"])
		{
			[result appendString:imgDateStr];
			i++;
		}
		else if ([[filter substringWithRange:NSMakeRange(i,2)] isEqualToString:@"%e"])
		{
			[result appendString:imgFileExt];
			i++;
		}
		else
		{
			[result appendString:[filter substringWithRange:NSMakeRange(i,1)]];
		}
		
		
	}
	
	
	// Why don't I need to retain the last result?
	
	NSLog(@"Result: %@", result);
	return result;
}

- (ExportPluginProgress *)progress
{
	return &mProgress;
}

- (void)lockProgress
{
	[mProgressLock lock];
}

- (void)unlockProgress
{
	[mProgressLock unlock];
}

- (void)cancelExport
{
	mCancelExport = YES;
}

- (NSString *)name
{
	return @"Custom iPhoto Exporter";
}
	

- (BOOL)testMethod:(int)num othernum:(int)theothernum
{
	return num == 5;
}

@end
